package com.smedi.ismedi.inmail.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.MessageRecord;
import com.smedi.ismedi.inmail.core.domain.repository.MessageRecordRepository;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.model.MessageRecordEntity;
import com.smedi.ismedi.inmail.core.port.adapter.persistence.mybatis.mapper.MessageRecordMapper;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author u
 */
@Repository
@AllArgsConstructor
public class MessageRecordRepositoryImpl extends ServiceImpl<MessageRecordMapper, MessageRecordEntity> implements MessageRecordRepository, IService<MessageRecordEntity> {
    private final DozerUtil dozerUtil;

    @Override
    public List<MessageRecord> doList(List<Long> ids) {
        return dozerUtil.convertor(listByIds(ids), MessageRecord.class);
    }

    @Override
    public MessageRecord doQuery(Long id) {
        return dozerUtil.convertor(getById(id), MessageRecord.class);
    }

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public List<MessageRecord> doInsertList(List<MessageRecord> messageRecords) {
        List<MessageRecordEntity> messageRecordEntities = dozerUtil.convertor(messageRecords, MessageRecordEntity.class);
        for(MessageRecordEntity messageRecordEntity:messageRecordEntities){
            messageRecordEntity.setId(null);
            messageRecordEntity.setPushTime(LocalDateTime.now());
        }
        saveBatch(messageRecordEntities);
        return dozerUtil.convertor(messageRecordEntities, MessageRecord.class);
    }

    @Override
    public List<MessageRecord> doUpdateList(List<MessageRecord> messageRecords) {
        List<MessageRecordEntity> entities = dozerUtil.convertor(messageRecords, MessageRecordEntity.class);
        updateBatchById(entities);
        return dozerUtil.convertor(entities, MessageRecord.class);
    }

    @Override
    public MessageRecord doUpdate(MessageRecord messageRecord) {
        MessageRecordEntity entity = dozerUtil.convertor(messageRecord, MessageRecordEntity.class);
        updateById(entity);
        return dozerUtil.convertor(entity, MessageRecord.class);
    }

    @Override
    public Boolean doDelete(List<Long> ids) {
        return removeByIds(ids);
    }
}